package com.example.test02;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONObject;

import java.io.IOException;

public class LoginActivity extends AppCompatActivity {

    private EditText editTextUsername;
    private EditText editTextPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //注册
        TextView registerText = findViewById(R.id.tv_register);
        registerText.setOnClickListener(v -> {
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
        });

        // 获取输入框的引用
        editTextUsername = findViewById(R.id.editTextUsername); // 请确保XML中的EditText ID与此一致
        editTextPassword = findViewById(R.id.editTextPassword); // 请确保XML中的EditText ID与此一致

        Button loginButton = findViewById(R.id.loginButton);
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取用户输入的账号和密码
                String username = editTextUsername.getText().toString();
                String password = editTextPassword.getText().toString();

                // 调用登录方法
                login(username, password);
            }
        });
    }

    private void login(String phone, String password) {
        // 创建 OkHttpClient 实例
        OkHttpClient client = new OkHttpClient();

        // 构建请求体
        FormBody body = new FormBody.Builder()
                .add("phone", phone)
                .add("password", password)
                .build();

        // 构建请求
        Request request = new Request.Builder()
                .url("http://120.26.59.7:17321/api/user/login")
                .post(body)
                .build();

        // 发起异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> {
                    Toast.makeText(LoginActivity.this, "网络请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    runOnUiThread(() -> {
                        Toast.makeText(LoginActivity.this, "服务器返回错误: " + response.code(), Toast.LENGTH_SHORT).show();
                    });
                    return;
                }

                // 获取响应体
                String responseData = response.body().string();
                try {
                    JSONObject jsonResponse = new JSONObject(responseData);
                    int code = jsonResponse.getInt("code");
                    String message = jsonResponse.getString("message");

                    if (code == 0) {
                        // 请求成功，处理 data 数据
                        JSONObject data = jsonResponse.getJSONObject("data");
                        JSONObject tokenObj = data.getJSONObject("saTokenInfo");
                        String token = tokenObj.getString("tokenValue");
                        int userId = data.getInt("userId");
                        String userName = data.getString("username");
                        String userPhone = data.getString("phone");

                        // 缓存数据
                        cacheUserData(token, userId, userName, userPhone);

                        // 跳转到主页面或其他操作
                        runOnUiThread(() -> {
                            Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                            // 示例：跳转到主页面
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                        });
                    } else {
                        // 请求失败，显示错误信息
                        runOnUiThread(() -> {
                            Toast.makeText(LoginActivity.this, "登录失败: " + message, Toast.LENGTH_SHORT).show();
                        });
                    }
                } catch (Exception e) {
                    runOnUiThread(() -> {
                        Toast.makeText(LoginActivity.this, "解析响应数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }

    private void cacheUserData(String token, int userId, String userName, String phone) {
        // 使用 SharedPreferences 缓存用户数据
        SharedPreferences sharedPreferences = getSharedPreferences("UserPrefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("token", token);
        editor.putInt("userId", userId);
        editor.putString("userName", userName);
        editor.putString("phone", phone);
        editor.apply();
    }
}
